# -*- coding: utf-8 -*-
from odoo import models, api, fields, tools
from odoo.exceptions import UserError
import re


class product_plan(models.Model):

    _name = "proman.product_plan"
    _description = "产品规模"
    _table = "proman_product_plan"
    _order = "sequence"
    _inherit =  ['mail.thread', 'mail.activity.mixin', 'image.mixin']

    sequence = fields.Integer(string="排序",translate = 0)
    name = fields.Char(string="产品规模名称",help = '请输入产品规模名称',readonly = 1,store = 1,translate = 0)
    product_temp_id = fields.Many2one(string="模板名称",help = '请选择模板名称',comodel_name = 'proman.product_temp',translate = 0)
    year = fields.Date(string="年度",translate = 0)
    manage_department_id = fields.Many2one(string="管理机构",comodel_name = 'hr.department',default = lambda self: self.env.user.default_department,translate = 0)
    company_id = fields.Many2one(string="所属公司",comodel_name = 'res.company',default = lambda self:self.env.company,required = 1,translate = 0)
    project_id = fields.Many2one(string="项目名称",comodel_name = 'proman.project_base',related = 'product_temp_id.project_id',readonly = 1,store = 1,translate = 0)
    project_stage_id = fields.Many2one(string="项目阶段",comodel_name = 'proman.stage_category',default = lambda self:self.env['proman.stage_category'].search([('name','=','可行性研究')]),translate = 0)
    region_id = fields.Many2one(string="省市县区",comodel_name = 'setcent.region',domain = lambda self: [('id', 'in', self.env['proman.township_village'].search([]).region_id.ids)],translate = 0)
    partner_id = fields.Many2one(string="相关单位",comodel_name = 'res.partner',domain = [('is_company','=',True)],translate = 0)
    user_id = fields.Many2one(string="部门负责人",comodel_name = 'res.users',translate = 0)
    create_department_id = fields.Many2one(string="录入部门",comodel_name = 'hr.department',translate = 0)
    url = fields.Char(string="相关链接",translate = 0)
    image = fields.Binary(string="相关照片1",translate = 0)
    image1 = fields.Binary(string="相关照片2",translate = 0)
    product_plan_items = fields.One2many(string="产品清单",comodel_name = 'proman.product_plan_item',inverse_name = 'main_id',copy = 1,translate = 0)
    attachment = fields.Many2many(string="相关附件",comodel_name = 'ir.attachment',translate = 0)
    state = fields.Selection(string="状态",selection = [('1', '草稿'), ('2', '提交'), ('3', '审核')],default='1',translate = 0)
    memo = fields.Html(string="备注说明",translate = 0)
    is_copy = fields.Boolean(string="是否为复制记录",default = 0,translate = 0)

    @api.onchange("year","region_id")
    def get_current_name(self):
        for plan in self:
            year = str(plan.year.year)+'年度-' if plan.year else ''
            region_info = str(plan.region_id.display_name).replace('/','') +"-" if plan.region_id else ''
            pattern = re.compile(r'\s+')
            region_info = re.sub(pattern, '', region_info)
            m_name = self._description + '表' if '表' not in self._description else self._description
            plan.name = year + region_info + m_name
    @api.onchange('product_temp_id')
    def compute_items_fields(self):
        for record in self:
            record.product_plan_items = False
            product_plan_items = []
            if record.product_temp_id:
                # 主表
                record.project_id = record.product_temp_id.project_id
                # 明细
                temp_product_plan_items = self.env['proman.product_temp_item'].sudo().search([('main_id', '=', record.product_temp_id.id)], order='sequence')

                for temp_product_plan_item in temp_product_plan_items:
                    product_plan_item = {
                        'indicator_category_id': temp_product_plan_item.indicator_category_id.id,
                        "indicator_id": temp_product_plan_item.indicator_id.id,
                        "memo": temp_product_plan_item.memo,
                        'uom_id': temp_product_plan_item.uom_id.id,
                    }
                    product_plan_items.append((0, 0, product_plan_item))
                record.update({
                    "product_plan_items": product_plan_items,
                })

    def button1(self):
        if self.state == '1':
            self.write({'state': '2'})
        # 审核
    def button2(self):
        if self.state == '2':
            self.write({'state': '3'})
        # 退回
    def button3(self):
        if self.state == '2':
            self.write({'state': '1'})

        # 反审核
    def button4(self):
        if self.state == '3':
            self.write({'state': '2'})
    @api.model
    def create(self, vals):
        old_name = vals.get("name", "")
        if vals.get("is_copy", False) and old_name:
            vals.update({"name": old_name + "_复制"})
        return super(product_plan, self).create(vals)
    def write(self, vals):
        vals['is_copy'] = False
        return super(product_plan, self).write(vals)

    @api.returns('self', lambda value: value.id)
    def copy(self, default=None):
        self.ensure_one()
        default = dict(default or {})
        if 'is_copy' not in default:
            default['is_copy'] = True
        return super(product_plan, self).copy(default=default)
    def unlink(self):
        for record in self:
            if record.state != '1':
                raise UserError("非草稿数据，不可删除，请取消并检查！")
        res = super(product_plan, self).unlink()
        return res
